import 'package:flutter/material.dart';
// import 'package:flutter_svg/flutter_svg.dart';
import 'package:vector_math/vector_math_64.dart' as vector_math;
import 'package:jovial_svg/jovial_svg.dart'; //svg
import 'package:matrix_gesture_detector/matrix_gesture_detector.dart';

// 定义主页面的有状态Widget类
class DemoPage extends StatefulWidget {
  @override
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {
  String selectedItem =
      '<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="40" fill="red" /></svg>'; // 写死的selectedItem
  List<Map<String, dynamic>> pointData = [
    {
      'xaxis': '50',
      'yaxis': '50',
      'loopNum': '1',
      'dotNum': '1',
      'svgType': '类型A',
      'svgUrl':
          'https://hujingyu.rupeng119.com:8005/monitor/2023/07/27/1_20230727092944A542.svg'
    },
    {
      'xaxis': '55',
      'yaxis': '55',
      'loopNum': '1',
      'dotNum': '2',
      'svgType': '类型B',
      'svgUrl':
          'https://hujingyu.rupeng119.com:8005/monitor/2023/07/27/1_20230727092944A542.svg'
    },
  ]; // 写死的pointData
  ValueNotifier<Matrix4> matrixNotifier = ValueNotifier(Matrix4.identity());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SVG Demo'),
      ),
      body: Column(
        children: [
          // 上部分区域，占20%，显示文字
          Expanded(
            flex: 2,
            child: Center(
              child: Text(
                'SVG Demo',
                style: TextStyle(fontSize: 20),
              ),
            ),
          ),
          // 下部分区域，占80%，显示SVG图及点位
          Expanded(
            flex: 8,
            child: _buildRightContent(),
          ),
        ],
      ),
    );
  }

  Widget _buildRightContent() {
    print('Building right content with selectedItem: $selectedItem');
    String selectedDescription =
        '<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="40" fill="red" /></svg>'; // 示例SVG字符串

    return FutureBuilder<ScalableImage>(
      future: Future.value(ScalableImage.fromSvgString(selectedDescription)),
      builder: (BuildContext context, AsyncSnapshot<ScalableImage> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.hasError) {
            return Text('Error loading SVG: ${snapshot.error}');
          }

          double originalWidth = snapshot.data!.width ?? 0.0;
          double originalHeight = snapshot.data!.height ?? 0.0;
          // double scaledWidth = originalWidth * 0.4;
          // double scaledHeight = originalHeight * 0.4;
          double scaledWidth = originalWidth;
          double scaledHeight = originalHeight;

          return LayoutBuilder(
            builder: (BuildContext context, BoxConstraints constraints) {
              return Stack(
                children: [
                  MatrixGestureDetector(
                    onMatrixUpdate: (Matrix4 matrix, Matrix4 translationMatrix,
                        Matrix4 scaleMatrix, Matrix4 rotationMatrix) {
                      matrixNotifier.value = matrix;
                    },
                    child: AnimatedBuilder(
                      animation: matrixNotifier,
                      builder: (BuildContext context, Widget? child) {
                        return Transform(
                          transform: matrixNotifier.value,
                          child: Center(
                            child: SizedBox(
                              width: constraints.maxWidth,
                              height: constraints.maxHeight,
                              child: Stack(
                                children: [
                                  ScalableImageWidget(
                                    si: snapshot.data!,
                                  ),
                                  if (pointData.isNotEmpty)
                                    ...pointData.map((point) {
                                      double x =
                                          double.tryParse(point['xaxis']) ?? 0;
                                      double y =
                                          double.tryParse(point['yaxis']) ?? 0;

                                      // x = x * 0.4;
                                      // y = y * 0.4;

                                      final vector_math.Vector4 pointVector =
                                          vector_math.Vector4(x, y, 0, 0);
                                      final vector_math.Vector4
                                          transformedVector4 = matrixNotifier
                                              .value
                                              .transform(pointVector);

                                      double transformedX =
                                          transformedVector4.x;
                                      double transformedY =
                                          transformedVector4.y;

                                      Widget pointIconWidget =
                                          _buildPointIconWidget(point);

                                      return Positioned(
                                        left: transformedX,
                                        top: transformedY,
                                        child: GestureDetector(
                                          child: pointIconWidget,
                                        ),
                                      );
                                    }).toList(),
                                ],
                              ),
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ],
              );
            },
          );
        } else {
          return CircularProgressIndicator();
        }
      },
    );
  }

  Widget _buildPointIconWidget(Map<String, dynamic> point) {
    return FutureBuilder<Widget>(
        future: _loadPointIcon(point),
        builder: (BuildContext context, AsyncSnapshot<Widget> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              return Text('加载点位图标出现错误');
            }
            return snapshot.data!;
          }
          return SizedBox();
        });
  }

  Future<Widget> _loadPointIcon(Map<String, dynamic> point) async {
    try {
      ScalableImage? scalableImage =
          await ScalableImage.fromSvgHttpUrl(Uri.parse(point['svgUrl']));
      return SizedBox(
        width: 10,
        height: 10,
        child: ScalableImageWidget(
          si: scalableImage!,
        ),
      );
    } catch (e) {
      print('加载点位图标SVG出错: $e');
      return SizedBox();
    }
  }
}

// 应用的主函数，Flutter应用的入口点
void main() {
  runApp(MyApp());
}

// 定义整个应用的根Widget类
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DemoPage(),
    );
  }
}
